package com.lucker.interceptor;

import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lucker.common.util.CommonStr;
import com.lucker.common.util.IPUtil;
import com.lucker.common.util.MD5;
import com.lucker.common.util.StringUtil;
import com.lucker.framework.constant.ResponseResultModel;
import com.lucker.framework.filter.BodyReaderHttpServletRequestWrapper;

public class CheckSignIntegceptors implements HandlerInterceptor {
	private static Logger			LOGGER					= LoggerFactory.getLogger(CheckSignIntegceptors.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String ip = IPUtil.getIPAddress(request);
	    String method = request.getMethod();
		 
        try {
        	if(StringUtil.isNotBlank(method) && StringUtil.equals(method.toLowerCase(), "get")) {
        		return true;
        	}
        	String timestamp = request.getHeader("timestamp");
        	String client_sign = request.getHeader("signature");
        	
        	if(StringUtil.isBlank(timestamp)) {
            	Object ret = JSONObject.toJSON(new ResponseResultModel<>(21996,"请求头中缺少公共参数: timestamp ", HttpStatus.OK));
            	response.setCharacterEncoding("UTF-8");
            	PrintWriter writer = response.getWriter();
				writer.append(ret.toString());
				writer.close();
				return Boolean.FALSE;
        	}
        	
        	if(StringUtil.isBlank(client_sign)) {
            	Object ret = JSONObject.toJSON(new ResponseResultModel<>(21998,"请求头中缺少签名 signature ", HttpStatus.OK));
            	response.setCharacterEncoding("UTF-8");
            	PrintWriter writer = response.getWriter();
				writer.append(ret.toString());
				writer.close();
				return Boolean.FALSE;
        	}
        	
        	JSONObject  tts = new JSONObject();
        	BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            String body = requestWrapper.getBody();
            //LOGGER.error("验签拦截器 BODY ==================>>>>>>>>>>>>   :  {} " , body);
            
            org.json.JSONObject json ;
            if(StringUtil.isBlank(body)) {
            	json = new org.json.JSONObject();
            }else {
            	json = new org.json.JSONObject(body);
            }
            //LOGGER.error("验签拦截器 拦截到的签名 ==================>>>>>>>>>>>>   :  {} " , client_sign);
            String sign = getSignature(json, timestamp);
        	if(!StringUtil.equals(client_sign, sign)) {
	    		Object ret = JSONObject.toJSON(new ResponseResultModel<>(21997,"签名错误", HttpStatus.OK));
	        	response.setCharacterEncoding("UTF-8");
	        	PrintWriter writer = response.getWriter();
				writer.append(ret.toString());
				writer.close();
				return Boolean.FALSE;        		
        	}
        	return true;
        }catch(Exception e) {
        	LOGGER.error("LogInterceptors 签名验证异常 ", e);
        	
        	Object ret = JSONObject.toJSON(new ResponseResultModel<>(21999,"签名错误, 请联系管理员", HttpStatus.OK));
        	response.setCharacterEncoding("UTF-8");
        	PrintWriter writer = response.getWriter();
			writer.append(ret.toString());
			writer.close();
			return Boolean.FALSE;    
			
			
        }
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		HttpServletRequest req = request;		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}

	public String getSignature(org.json.JSONObject jsonData, String timestamp) {
	    Map<String, String> sortedParams = new TreeMap<>();
	    sortedParams.put("timestamp", timestamp);
	    if (jsonData != null) {
	        Iterator<String> iterator = jsonData.keys();
	        while (iterator.hasNext()) {
	            String key = iterator.next();
	            String value = jsonData.optString(key);
	            sortedParams.put(key.toLowerCase(), value);
	        }
	    }
	    StringBuilder data = new StringBuilder();
	    Set<Map.Entry<String, String>> entry = sortedParams.entrySet();
	    for (Map.Entry<String, String> params : entry) {
	        data.append(params.getKey()).append('=').append(params.getValue());
	    }
	    data.append(CommonStr.CLIENT_SECRET_KEY);

    	//LOGGER.error("签名加密前 =============== > {}" , data.toString());
    	//LOGGER.error("签名加密后 =============== > {}" , MD5.passmd5(data.toString()));
	    return MD5.passmd5(data.toString());
	}
}
